<template>
  <div class="list-field-config">
    <je-panel v-bind="headOptions" ref="headPanel">
      <template #top>
        <je-table
          ref="navWrap"
          keep-source
          class="navWrap"
          border
          resizable
          :row-config="{ keyField: 'id' }"
          auto-resize
          show-header-overflow="ellipsis"
          :data="dataHeaderTable"
          :columns="arrShowField"
          size="mini"
          draggable
          @column-drop="columndrop"
          @resizable-change="resizeableChange"
        />
      </template>
      <template #tbar>
        <div class="top">
          <je-button type="text" @click="handleImport">
            <i class="fal fa-file-import"></i> 导入
          </je-button>
          <je-button type="text" @click="handleAdd({ type: 'morecolumn', name: '多表头' })">
            <i class="fal fa-plus-circle"></i> 添加多表头
          </je-button>
          <je-button type="text" @click="handleSave"> <i class="fal fa-save"></i> 保存 </je-button>
          <je-button type="text" @click="handleDelete">
            <i class="fal fa-times"></i> 删除
          </je-button>
          <je-button type="text" @click="handleSort">
            <i class="fal fal fa-sort-alpha-down"></i>排序整理</je-button
          >
          <je-button type="text" @click="handleJs(false)">
            <i
              class="fas fa-bolt"
              :style="`color:${
                changeJsListener(funcStore.funcBean.FUNCINFO_GRIDJSLISTENER) ? '#F4CE4A' : '#8d98ab'
              }`"
            ></i>
            列表 JS 事件</je-button
          >
          <je-button type="text" @click="handleSync">
            <i class="fal fal fa-copy"></i>与表单同步
          </je-button>
          <je-button type="text" @click="automaticallySelectQuery">
            <i class="fal fa-ballot-check"></i>自动选择关联查询列
          </je-button>
          <je-button type="text" @click="SelectDisplayColumn">
            <i class="fal fa-check-square"></i>选中展示列
          </je-button>
          <je-button type="text" @click="openTable">
            <i class="fal fa-book"></i>打开资源表
          </je-button>
          <div class="searchWrap">
            <je-input-search
              v-model:value.trim="searchValue"
              class="search"
              placeholder="搜索"
              allow-clear
              enter-button="搜索"
              style="width: 280px"
              @search="getData('search')"
            >
              <template #prefix> <i class="fal fa-search" /> </template>
            </je-input-search>
          </div>
        </div>
      </template>
      <template #default>
        <div class="tableWrap">
          <je-panel v-bind="tableOptions" ref="tablePanel">
            <template #right>
              <edit-field-config
                ref="editFieldConfig"
                v-model:record-data="selectField"
                :func-bean="recordData"
                @changeEditFieldConfig="changeEditFieldConfig"
              />
            </template>
            <template #default>
              <je-table
                ref="xTable"
                class="table"
                border
                stripe
                auto-resize
                sync-resize
                show-overflow="ellipsis"
                keep-source
                show-header-overflow
                resizable
                height="100%"
                align="center"
                draggable
                :edit-config="{
                  trigger: 'click',
                  mode: 'cell',
                  showUpdateStatus: true,
                }"
                :row-config="{
                  isCurrent: true,
                  isHover: true,
                  keyField: 'JE_CORE_RESOURCECOLUMN_ID',
                }"
                :loading="loading"
                :row-class-name="rowClassName"
                :cell-class-name="cellClassName"
                :store="tableData"
                :field-config="filedsArr"
                size="mini"
                @drop="listFieldItemDrop"
                @current-change="onClickRow"
              >
                <je-table-column type="checkbox" width="40" fixed="left"></je-table-column>
                <je-table-column
                  field="SY_ORDERINDEX"
                  title="序号"
                  width="60"
                  fixed="left"
                  :edit-render="{}"
                >
                  <template #edit="{ row }">
                    {{ row.SY_ORDERINDEX }}
                  </template>
                </je-table-column>
                <je-table-column
                  field="RESOURCECOLUMN_CODE"
                  title="编码"
                  width="220"
                  align="left"
                  fixed="left"
                >
                  <template #default="{ row }">
                    <div
                      class="eventWrap"
                      @dblclick.stop="showEditFieldConfig(row, 'right')"
                      v-html="formatHightText(searchValue, row.RESOURCECOLUMN_CODE)"
                    />
                  </template>
                </je-table-column>
                <je-table-column
                  field="RESOURCECOLUMN_NAME"
                  title="名称"
                  fixed="left"
                  align="left"
                  min-width="140"
                  :edit-render="{ autofocus: '.ant-input' }"
                >
                  <template #default="{ row }">
                    <span v-html="formatHightText(searchValue, row.RESOURCECOLUMN_NAME)"></span>
                  </template>
                  <template #edit="{ row }">
                    <je-input v-model:value="row.RESOURCECOLUMN_NAME" />
                  </template>
                </je-table-column>
                <je-table-column
                  field="RESOURCECOLUMN_WIDTH"
                  title="列宽"
                  min-width="100"
                  :edit-render="{ autofocus: '.ant-input-number-input' }"
                >
                  <template #edit="{ row }">
                    <je-input-number
                      v-model:value="row.RESOURCECOLUMN_WIDTH"
                      :min="0"
                      style="width: 100%"
                      @focus="handFocus($event)"
                    />
                  </template>
                </je-table-column>
                <je-table-column
                  field="RESOURCECOLUMN_HIDDEN"
                  title="隐藏"
                  width="80"
                  type="switch"
                />
                <je-table-column
                  field="RESOURCECOLUMN_ALLOWEDIT"
                  title="编辑"
                  width="80"
                  type="switch"
                />
                <je-table-column
                  field="RESOURCECOLUMN_AUTO_FILL"
                  title="自动填充"
                  width="80"
                  type="switch"
                />
                <je-table-column
                  field="RESOURCECOLUMN_LAZYLOAD"
                  title="加载项"
                  width="80"
                  type="switch"
                />

                <je-table-column
                  field="RESOURCECOLUMN_ALIGN_TITLE"
                  min-width="200"
                  type="switch"
                  :switch-config="{
                    layout: 'buttons',
                    options: COLUMN_ALIFN_LIST,
                  }"
                >
                  <template #header>
                    标题对齐方式
                    <i
                      style="font-size: 16px; cursor: pointer"
                      class="fal fa-pencil"
                      @click="
                        showModal({
                          type: 'updateOneFieldValue',
                          data: {
                            name: '批量数据修改',
                            fieldName: 'RESOURCECOLUMN_ALIGN_TITLE',
                          },
                        })
                      "
                    ></i>
                  </template>
                </je-table-column>
                <je-table-column
                  field="RESOURCECOLUMN_ALIGN"
                  min-width="200"
                  type="switch"
                  :switch-config="{
                    layout: 'buttons',
                    options: COLUMN_ALIFN_LIST,
                  }"
                >
                  <template #header>
                    数据对齐方式
                    <i
                      style="font-size: 16px; cursor: pointer"
                      class="fal fa-pencil"
                      @click="
                        showModal({
                          type: 'updateOneFieldValue',
                          data: {
                            name: '批量数据修改',
                            fieldName: 'RESOURCECOLUMN_ALIGN',
                          },
                        })
                      "
                    ></i>
                  </template>
                </je-table-column>
                <je-table-column title="事件" width="60" field="RESOURCECOLUMN_JSLISTENER">
                  <template #default="{ row }">
                    <je-tooltip placement="top" title="编辑">
                      <div class="iconWrap" @click="handleJs(row)"
                        ><i
                          class="fas fa-bolt"
                          :style="`color:${
                            changeJsListener(row.RESOURCECOLUMN_JSLISTENER) ? '#F4CE4A' : '#8d98ab'
                          }`"
                        ></i
                      ></div>
                    </je-tooltip>
                  </template>
                </je-table-column>
                <je-table-column
                  field="RESOURCECOLUMN_COLUMNQUERYTYPE"
                  title="查询类型"
                  min-width="140"
                  :edit-render="{}"
                >
                  <template #edit="{ row }">
                    <je-select
                      v-model:value="row.RESOURCECOLUMN_COLUMNQUERYTYPE"
                      allow-clear
                      config-info="JE_FUNC_QUERYTYPE,row.RESOURCECOLUMN_COLUMNQUERYTYPE,code,S"
                      :querys="[
                        {
                          code: 'DICTIONARYITEM_ITEMCODE',
                          type: 'in',
                          value: ['=', 'like', 'no'],
                        },
                      ]"
                    />
                  </template>
                  <template #default="{ row }">
                    {{
                      getSelectCodeToLabel('JE_FUNC_QUERYTYPE', row.RESOURCECOLUMN_COLUMNQUERYTYPE)
                    }}
                  </template>
                </je-table-column>
                <je-table-column
                  field="RESOURCECOLUMN_QUERYTYPE"
                  title="快速查询"
                  min-width="140"
                  type="switch"
                />
                <je-table-column
                  field="RESOURCECOLUMN_ENABLEUPDATE"
                  title="批量更新"
                  width="100"
                  type="switch"
                >
                  <template #header>
                    <div>
                      批量更新 <i class="fas fa-flower" style="color: rgb(235, 235, 235)"></i>
                    </div>
                  </template>
                </je-table-column>
                <!-- <je-table-column
                  field="RESOURCECOLUMN_IDIT"
                  title="允许展示"
                  width="100"
                  type="switch"
                >
                  <template #header>
                    <div>
                      允许展示 <i class="fas fa-flower" style="color: rgb(235, 235, 235)"></i>
                    </div>
                  </template>
                </je-table-column> -->
                <je-table-column
                  field="RESOURCECOLUMN_QUICKQUERY"
                  title="关联查询列"
                  width="120"
                  type="switch"
                />
                <je-table-column
                  field="RESOURCECOLUMN_QUICKQUERYTYPE"
                  title="关联查询时快速查询"
                  min-width="180"
                  type="switch"
                />
                <je-table-column
                  field="RESOURCECOLUMN_MORECOLUMNNAME"
                  title="所属多表头"
                  min-width="180"
                  :edit-render="{}"
                >
                  <template #edit="{ row }">
                    <je-select
                      v-model:value="row.RESOURCECOLUMN_MORECOLUMNNAME"
                      allow-clear
                      :options="funcStore.groupColumns"
                    />
                  </template>
                  <template #default="{ row }">{{
                    getSelectLabel(row.RESOURCECOLUMN_MORECOLUMNNAME, funcStore.groupColumns)
                  }}</template>
                </je-table-column>
                <je-table-column title="索引" min-width="140">
                  <template #default="{ row }">
                    <div v-if="row.RESOURCECOLUMN_XTYPE === 'uxcolumn'">
                      <div v-if="row.RESOURCECOLUMN_INDEX === '0'" class="txt">
                        未索引，<span class="create" @click="handleCreateIndex(row)">创建</span>
                      </div>
                      <div v-if="row.RESOURCECOLUMN_INDEX === '1'" class="txt">
                        已索引，<span class="remove" @click="handleDeleteIndex(row)">删除</span>
                      </div>
                    </div>
                  </template>
                </je-table-column>
                <je-table-column
                  field="RESOURCECOLUMN_COLUMNTIP"
                  title="提示"
                  width="80"
                  type="switch"
                />
                <je-table-column
                  field="RESOURCECOLUMN_LOCKED"
                  title="锁定列"
                  width="140"
                  :edit-render="{}"
                >
                  <template #edit="{ row }">
                    <je-select
                      v-model:value="row.RESOURCECOLUMN_LOCKED"
                      allow-clear
                      :options="arrResourceColumnLocked"
                    />
                  </template>
                  <template #default="{ row }">{{
                    getSelectLabel(row.RESOURCECOLUMN_LOCKED, arrResourceColumnLocked)
                  }}</template>
                </je-table-column>
                <je-table-column
                  field="RESOURCECOLUMN_ORDER"
                  title="排序"
                  width="80"
                  type="switch"
                />

                <je-table-column
                  field="RESOURCECOLUMN_MULTIROWS"
                  title="多行显示"
                  width="100"
                  type="switch"
                />

                <!-- <je-table-column
                  field="RESOURCECOLUMN_MERGE"
                  title="合并单元格"
                  width="110"
                  type="switch"
                >
                  <template #header>
                    <div>
                      合并单元格 <i class="fas fa-flower" style="color: rgb(235, 235, 235)"></i>
                    </div>
                  </template>
                </je-table-column> -->
                <je-table-column field="RESOURCECOLUMN_XTYPE" title="类型" width="140">
                  <template #default="{ row }">{{
                    getSelectCodeToLabel('JE_FUNC_COLUMN_XTYPE', row.RESOURCECOLUMN_XTYPE)
                  }}</template>
                </je-table-column>
              </je-table>
            </template>
          </je-panel>
        </div>
      </template>
    </je-panel>

    <div v-if="modalOption.modalFlag">
      <component
        :is="modalOption.activeModal"
        :visble="modalOption.modalFlag"
        :record-data="modalOption.recordData"
        @changeModal="changeModal"
        @changeData="modalOption.modalFlag = false"
      ></component>
    </div>
  </div>
</template>

<script>
  import {
    ref,
    reactive,
    toRefs,
    defineComponent,
    onMounted,
    watch,
    onBeforeMount,
    nextTick,
  } from 'vue';
  import { Layout } from 'ant-design-vue';
  import {
    Grid,
    Modal,
    Panel,
    Button,
    Checkbox,
    Radio,
    Input,
    InputNumber,
    Form,
    Select,
    Data,
    Menu,
    Dropdown,
    Tooltip,
  } from '@jecloud/ui';

  import EditFieldConfig from '@/components/list-field-config/components/edit-field-config.vue';

  import { LIST_FIELD_CONFIG_COMPONENTS } from '@/helper/list-field-config-components';

  import { UpdataOneFieldModal } from './hooks/update-one-field.jsx';

  import VueEvent from '@/helper/event';

  import {
    ListFieldConfigGet,
    ListFieldConfigImport,
    ListFieldConfigUpdate,
    ListFieldConfigRemove,
    ListFieldConfigAddMorecolumn,
    ListFieldConfigSync,
    ListFieldConfigCreateIndex,
    ListFieldConfigRemoveIndex,
    // addSignAndPostilColumn,
  } from '@/api/index';

  import { RESOURCECOLUMN_LOCKED } from '@/helper/constant';

  import { listenerEditorModal } from '@/helper/index.js';

  import { formatHightText } from '@/helper/common.js';

  import { useFuncStore } from '@/store/func-store';
  import {
    getDDItemInfo,
    isNotEmpty,
    loadDDItemByCodes,
    getAxiosBaseURL,
    getDDItemList,
  } from '@jecloud/utils';
  import { useGlobalStore } from '@common/store/global-store';

  export default defineComponent({
    name: 'ListFieldConfig',
    components: {
      EditFieldConfig,
      JeButton: Button,
      JeInput: Input,
      JeInputNumber: InputNumber,
      JeInputSearch: Input.Search,
      JeCheckbox: Checkbox,
      JeRadio: Radio,
      JeRadioGroup: Radio.Group,
      JeRadioButton: Radio.Button,
      JeSelect: Select,
      JeSelectOption: Select.Option,
      JeTable: Grid,
      JeTableGroup: Grid.Group,
      JeTableColumn: Grid.Column,
      JeDropdown: Dropdown,
      JeMenu: Menu,
      JeMenuItem: Menu.Item,
      JeForm: Form,
      JeFormItem: Form.Item,
      JeModal: Modal,
      JeLayout: Layout,
      JeLayoutSider: Layout.Sider,
      JeLayoutContent: Layout.Content,
      JeTooltip: Tooltip,
      JePanel: Panel,
      ...LIST_FIELD_CONFIG_COMPONENTS,
    },
    props: {
      recordData: {
        type: Object,
        default: () => {},
      },
    },
    emits: [],
    setup(props) {
      const funcStore = useFuncStore();
      const dataHeaderTable = ref([]);
      const state = reactive({
        showStatus: false,
        dataHeaderTable: [],
        navWrap: ref(),
        xTable: ref(),
        filedsArr: [],
        // isView: funcStore.funcBean.FUNCINFO_FUNCTYPE == 'VIEW', // 是否是视图做的功能
        editFieldConfig: ref(),
        searchValue: '',
        collapsed: true,
        tableData: Data.Store.useGridStore({
          data: [],
        }),
        selectTableData: [],
        loading: true,
        funcId: props.recordData.JE_CORE_FUNCINFO_ID,
        selectField: {},
        arrShowField: [],
        arrResourceColumnLocked: RESOURCECOLUMN_LOCKED,
        arrResourceColumnMoreColumnName: [],
        headPanel: ref(),
        headOptions: {
          top: { size: 42, hidden: false, split: false },
        },
        tablePanel: ref(),
        tableOptions: {
          right: {
            size: 540,
            split: true,
            collapsible: true,
            collapsed: true,
            minSize: 540,
          },
        },
        formatHightText,
        columnsArr: [],
        newDropArr: [],
        levelData: [], // 层级显示数据
        flag: true, // 防止导入按钮重复提交的变量
        COLUMN_ALIFN_LIST: [],
      });

      const modalOption = reactive({
        modalFlag: false, // 默认modal都是隐藏的false
        activeModal: '', // 默认没有激活的弹窗类型
      });

      const menuActive = reactive({ show: '', recordData: props.recordData });

      //弹出关闭回调
      const btnClick = (obj) => {
        if (obj.type == 'close') {
          menuActive.show = '';
        }
      };

      //弹出代码编辑器
      const handleJs = (row) => {
        if (row) {
          listenerEditorModal({
            funcId: props.recordData.id,
            funcCode: props.recordData.code,
            funcName: props.recordData.text,
            onId: row.JE_CORE_RESOURCECOLUMN_ID,
            eventType: 'column',
            title: '列事件',
            callback: (obj) => {
              row.RESOURCECOLUMN_JSLISTENER = obj.data;
            },
          });
        } else {
          listenerEditorModal({
            funcId: props.recordData.id,
            funcCode: props.recordData.code,
            funcName: props.recordData.text,
            eventType: 'grid',
            title: '列表JS事件',
            callback: (obj) => {
              funcStore.funcBean.FUNCINFO_GRIDJSLISTENER = obj.data;
            },
          });
        }
      };
      watch(
        () => state.searchValue,
        (newVal) => {
          if (!newVal) {
            state.searchType = false;
          }
        },
      );
      watch(
        () => state.arrShowField,
        (newValue, oldData) => {
          state.arrShowField = newValue || oldData;
        },
        { deep: true },
      );
      // 监听头部的表头
      watch(
        () => state.levelData,
        (newValue) => {
          state.levelData = newValue;
          if (!state.levelData.length) {
            state.headOptions.top.size = 0;
            return false;
          }
          const aLength = methods.calculationLevel(state.levelData);
          state.headOptions.top.size = aLength > 1 ? 32 * aLength + 20 : 52;
        },
        { deep: true },
      );

      const methods = {
        // 打开资源表
        openTable() {
          if (!props.recordData.JE_CORE_RESOURCETABLE_ID) {
            Modal.alert('资源表不存在！', 'error');
            return false;
          }
          // 获取产品ID
          const { id } = funcStore.product;
          const { activePlan } = useGlobalStore();
          window.open(
            `${getAxiosBaseURL()}/#/${activePlan}/app/JE_CORE_TABLE?productId=${id}&id=${
              props.recordData.JE_CORE_RESOURCETABLE_ID
            }`,
          );
        },
        //自动选择关联查询列
        automaticallySelectQuery() {
          state.tableData.data.forEach((item) => {
            if (item.RESOURCECOLUMN_HIDDEN == '0') {
              item.RESOURCECOLUMN_QUICKQUERY = '1';
            }
          });
        },
        // 选中展示列
        SelectDisplayColumn() {
          const selectTableData = state.xTable.getSelectedRecords();
          const newSelectData = [];
          state.showStatus = !state.showStatus;
          state.tableData.data.forEach((item) => {
            if (item.RESOURCECOLUMN_HIDDEN == '0') {
              const newItem = selectTableData.find(
                (_item) => item.JE_CORE_RESOURCEFIELD_ID == _item.JE_CORE_RESOURCEFIELD_ID,
              );
              !newItem && newSelectData.push(item);
              state.showStatus && state.xTable.setSelectRow(item);
              !state.showStatus && state.xTable.setSelectRow(item, false);
            }
          });
        },

        handFocus(e) {
          e.currentTarget.select();
        },
        changeJsListener(data) {
          const parseData = data ? JSON.parse(data) : [];
          let eventType = false;
          parseData.forEach((item) => {
            if (item.fire == '1') {
              eventType = true;
            }
          });
          return eventType;
        },
        // 拖拽排序
        listFieldItemDrop() {
          state.tableData.data.forEach((item, index) => {
            item.SY_ORDERINDEX = index + 1;
          });
        },

        showModal(obj) {
          const selectTableData = state.xTable.getSelectedRecords();
          UpdataOneFieldModal({
            title: '批量数据修改',
            recordData: obj.data,
            callback: (obj) => {
              if (obj.isOnlyChecked == '1') {
                state.tableData.data.forEach((item) => {
                  const findIndex = selectTableData.findIndex(
                    (item2) => item2.JE_CORE_RESOURCECOLUMN_ID === item.JE_CORE_RESOURCECOLUMN_ID,
                  );

                  if (findIndex !== -1) {
                    item[obj.fieldName] = obj.value;
                  }
                });
              } else {
                state.tableData.data.forEach((item) => {
                  item[obj.fieldName] = obj.value;
                });
              }
            },
          });
        },

        changeModal(obj) {
          modalOption.modalFlag = obj.visible;

          // 更改表格字段的值
          if (obj.type === 'refreshData') {
            methods.getData();
          }
        },

        showEditFieldConfig(row, pos) {
          if (row.JE_CORE_RESOURCECOLUMN_ID === state.selectField.JE_CORE_RESOURCECOLUMN_ID) {
            state.tableOptions[pos].collapsed = !state.tableOptions[pos].collapsed;
          } else {
            state.tableOptions[pos].collapsed = false;
          }

          state.selectField = row;
        },
        getSelectCodeToLabel(dictionary, code) {
          const item = getDDItemInfo(dictionary, code);

          if (isNotEmpty(item)) {
            return item.text;
          }
          return '';
        },
        onClickRow({ row }) {
          methods.showEditFieldConfig2(row, 'right');
        },
        showEditFieldConfig2(row, pos) {
          state.selectField = row;
          if (state.tableOptions[pos].collapsed) {
            return false;
          }
        },

        changeEditFieldConfig(obj) {
          state.tableOptions['right'].collapsed = !obj.visible;
          obj.isRefresh && methods.getData();
        },
        flatten(arr, id) {
          let morecolumnStr = id || '';
          arr.map((item) => {
            if (item.children && item.children.length) {
              methods.flatten(item.children, item.field);
              item.morecolumn = morecolumnStr;
              state.newDropArr.push(item);
            } else {
              item.morecolumn = morecolumnStr;
              state.newDropArr.push(item);
            }
          });
          return state.newDropArr;
        },
        columndrop() {
          state.newDropArr = [];
          let arr1 = state.navWrap.$plugin.getTableColumn().collectColumn;
          // 将arr
          let arr = methods.flatten(arr1, '');
          const aLength = methods.calculationLevel(arr1);
          state.headOptions.top.size = aLength > 1 ? 32 * aLength + 20 : 52;
          state.tableData.data.forEach((item) => {
            const index = arr.findIndex((item1) => item1.field === item.RESOURCECOLUMN_CODE);
            item.SY_ORDERINDEX = index + 1;
            item.RESOURCECOLUMN_MORECOLUMNNAME = arr[index] ? arr[index].morecolumn : '';
          });
        },

        resizeableChange({ column }) {
          let findIndex = state.tableData.data.findIndex(
            (item) => item.RESOURCECOLUMN_CODE === column.field,
          );
          if (findIndex !== -1) {
            state.tableData.data[findIndex].RESOURCECOLUMN_WIDTH = column.renderWidth;
          }
        },

        headerCellStyle() {
          return { 'border-right': '1px solid #e6e6e6' };
        },

        handleAdd(obj) {
          const params = {
            tableCode: 'JE_CORE_RESOURCECOLUMN',
            RESOURCECOLUMN_FUNCINFO_ID: state.funcId,
            RESOURCECOLUMN_XTYPE: obj.type,
            RESOURCECOLUMN_NAME: obj.name,
          };

          ListFieldConfigAddMorecolumn(params)
            .then((res) => {
              state.tableData.insert(res.data);
              Modal.message(res.message, 'success');
              setTimeout(() => {
                methods.getData();
              }, 100);
            })
            .catch((error) => {
              Modal.alert(error.message, 'error');
            });
        },

        // 保存
        handleSave() {
          state.tableData.data.forEach((item) => {
            if (item.RESOURCECOLUMN_HIDDEN == '0') {
              item.RESOURCECOLUMN_LAZYLOAD = '1';
            }
          });
          const updateRecords = state.tableData.getChanges();
          if (updateRecords.length === 0) {
            Modal.message('无数据操作!', 'info');
            return false;
          }
          const changeData = [];
          const data = [];
          updateRecords.forEach((item) => {
            data.push(item._record);
            const changeItem = {
              JE_CORE_RESOURCECOLUMN_ID: item._record.JE_CORE_RESOURCECOLUMN_ID,
            };
            Object.keys(item).forEach((key) => {
              if (key != '_record') {
                changeItem[key] = item[key].newValue || '';
              }
            });
            changeData.push(changeItem);
          });
          ListFieldConfigUpdate({
            funcId: state.funcId,
            strData: JSON.stringify(changeData),
          })
            .then((res) => {
              Modal.message(res.message, 'success');
              methods.getData();
              data.forEach((item) => {
                state.tableData.commitRecord(item);
              });

              // 这边保存完之后要处理顶部的数据
            })
            .catch((error) => {
              Modal.alert(error.message, 'error');
            });
        },
        // 格式化成字符串
        formatString(value, type) {
          if (!value) return '';
          if (typeof value == 'string') {
            return value;
          } else {
            if (type == 'join') {
              value = value.join(',');
            } else if (type == 'stringify') {
              value = JSON.stringify(value);
            }

            return value;
          }
        },
        handleImport() {
          if (!state.flag) return false;
          state.flag = false;
          let params = {
            RESOURCECOLUMN_FUNCINFO_ID: state.funcId,
          };

          ListFieldConfigImport(params)
            .then((res) => {
              state.flag = true;
              Modal.message(res.message, 'success');
              methods.getData();
            })
            .catch((error) => {
              state.flag = true;
              Modal.alert(error.message, 'error');
            });
        },

        getSelectLabel(value, list, valueProp = 'value', labelField = 'label') {
          const item = list.find((item) => item[valueProp] === value);
          return item ? item[labelField] : null;
        },

        getData(type) {
          state.loading = true;
          const params = {
            tableCode: 'JE_CORE_RESOURCECOLUMN',
            funcId: state.funcId,
            baseSql: ` and RESOURCECOLUMN_FUNCINFO_ID = '${state.funcId}'`,
            j_query: JSON.stringify({
              custom: [
                { code: 'RESOURCECOLUMN_FUNCINFO_ID', value: state.funcId, type: '=', cn: 'and' },
                {
                  type: 'and',
                  value: [
                    { code: 'RESOURCECOLUMN_CODE', type: 'like', value: state.searchValue },
                    {
                      cn: 'or',
                      code: 'RESOURCECOLUMN_NAME',
                      type: 'like',
                      value: state.searchValue,
                    },
                  ],
                },
              ],
              order: [{ code: 'SY_ORDERINDEX', type: 'ASC' }],
            }),
          };
          const arrResourceColumnMoreColumnName = [];

          ListFieldConfigGet(params)
            .then((res) => {
              state.filedsArr = [];
              if (res.data.rows && res.data.rows.length) {
                Object.keys(res.data.rows[0]).forEach((key) => {
                  !state.filedsArr.some((item) => item == key) && state.filedsArr.push(key);
                });
              }
              const tableGroup = [];
              const data = res.data.rows;
              const levelArr = [];
              data.forEach((item) => {
                item.RESOURCECOLUMN_MORECOLUMNNAME = item.RESOURCECOLUMN_MORECOLUMNNAME || '';
                // 标题颜色
                item.RESOURCECOLUMN_TITLECOLOR = item.RESOURCECOLUMN_TITLECOLOR || '';

                const {
                  RESOURCECOLUMN_CODE,
                  RESOURCECOLUMN_NAME,
                  RESOURCECOLUMN_WIDTH,
                  RESOURCECOLUMN_MORECOLUMNNAME,
                  RESOURCECOLUMN_ALIGN_TITLE,
                  RESOURCECOLUMN_HIDDEN,
                } = item;

                if (item.RESOURCECOLUMN_HIDDEN == '0') {
                  levelArr.push({
                    field: RESOURCECOLUMN_CODE,
                    code: RESOURCECOLUMN_CODE,
                    title: RESOURCECOLUMN_NAME,
                    group: RESOURCECOLUMN_MORECOLUMNNAME,
                  });
                }

                tableGroup.push({
                  field: RESOURCECOLUMN_CODE,
                  code: RESOURCECOLUMN_CODE,
                  title: RESOURCECOLUMN_NAME,
                  width: RESOURCECOLUMN_WIDTH,
                  group: RESOURCECOLUMN_MORECOLUMNNAME,
                  headerAlign: RESOURCECOLUMN_ALIGN_TITLE,
                  draggable: true,
                  visible: RESOURCECOLUMN_HIDDEN == '0',
                });

                if (item.RESOURCECOLUMN_XTYPE === 'morecolumn' && !type) {
                  arrResourceColumnMoreColumnName.push({
                    value: item.RESOURCECOLUMN_CODE,
                    label: item.RESOURCECOLUMN_NAME,
                  });
                }
              });
              state.arrShowField = JSON.parse(JSON.stringify(methods.formatTableArr(tableGroup)));
              state.levelData =
                (levelArr.length && JSON.parse(JSON.stringify(methods.formatTableArr(levelArr)))) ||
                [];
              state.tableData.fields = state.filedsArr;
              // 处理多表头，字段配置可以使用 type 这边做的处理就是搜索之后数据有误
              !type && (funcStore.groupColumns = arrResourceColumnMoreColumnName);
              state.tableData.loadData(data);
              state.loading = false;
              setTimeout(() => {
                // methods.formatHeaderArr(state.arrShowField, tableGroup);
                // 保存完之后呢，右侧面板不要隐藏，但是需要重新打开一下，这里先获取state.tableOptions['right'].collapsed
                // 目前的实现逻辑就是if collapsed = false,那state.selectField必定有值，在此点击一下
                if (!state.tableOptions['right'].collapsed && state.selectField) {
                  const { JE_CORE_RESOURCECOLUMN_ID } = state.selectField;
                  const arr = state.tableData.data.filter(
                    (item_) => item_.JE_CORE_RESOURCECOLUMN_ID == JE_CORE_RESOURCECOLUMN_ID,
                  );
                  state.selectField = arr && arr.length ? arr[0] : {};
                  methods.showEditFieldConfig2(state.selectField, 'right');
                }
              }, 0);
            })
            .catch((error) => {
              Modal.alert(error.message, 'error');
            });
        },
        formatTableArr(list, group = {}) {
          const code = group.code || '';
          let newArr = list.filter((item) => item.group == code);
          const { visible } = group;
          const changeCode = [];
          newArr.forEach((item) => {
            visible == false && changeCode.push(item.code);
            // 处理list数据
            const newList = visible == false ? methods.changeListVisible(list, changeCode) : list;
            item.children = methods.formatTableArr(newList, (group = item));
          });
          return newArr;
        },
        changeListVisible(list, data) {
          list.map((item) => {
            data.map((code) => {
              if (item.code == code) {
                item.visible = false;
              }
            });
          });
          return list;
        },
        calculationLevel(arr) {
          //递归计算树形数据最大的层级数
          let maxLevel = 0;
          !(function multiArr(arr, level) {
            ++level;
            maxLevel = Math.max(level, maxLevel);
            for (let i = 0; i < arr.length; i++) {
              let item = arr[i];
              item.level = level;
              if (item.children && item.children.length > 0) {
                multiArr(item.children, level);
              } else {
                delete item.children;
              }
            }
          })(arr, 0);
          return maxLevel;
        },
        // 格式话表头数据
        formatHeaderArr(targetArr) {
          if (!targetArr.length) {
            return [];
          }
          state.columnsArr = [];
          targetArr.forEach((item) => {
            // 说明这个是第一级,只要是group为空
            if (!item.group) {
              state.columnsArr.push(item);
            } else {
              //  不是一级,先将所属表头的数据拼接['morecolumn_1, 'morecolumn_2']
              state.columnsArr.forEach((_item, index) => {
                if (_item.code == item.group) {
                  state.columnsArr[index].children.push(_item);
                }
              });
            }
          });
        },
        // 与表单同步
        handleSync() {
          Modal.confirm(
            '根据编码同步对应表单字段的“名称”、“隐藏”、“序号(排序)”数据，确定同步吗？',
            () => {
              methods.doListSync();
            },
          );
        },

        handleSort() {
          if (state.searchValue) {
            Modal.alert(
              '当前列表数据存在搜索条件，请清除搜索条件查询全部字段数据后，再进行排序整理。',
              'warning',
            );
            return false;
          }
          const showTableData = state.tableData.data.filter(
            (item) => item.RESOURCECOLUMN_HIDDEN == '0',
          );

          let showStartIndex = 1;
          let hideStartIndex = showTableData.length + 1;

          state.tableData.data.forEach((item) => {
            if (item.RESOURCECOLUMN_HIDDEN == '1') {
              item.SY_ORDERINDEX = hideStartIndex++;
            } else {
              item.SY_ORDERINDEX = showStartIndex++;
            }
          });

          Modal.message('排序整理完成', 'success');
        },

        doListSync() {
          const params = {
            RESOURCECOLUMN_FUNCINFO_ID: state.funcId,
          };

          ListFieldConfigSync(params)
            .then((res) => {
              Modal.message(res.message, 'success');
              methods.getData();
            })
            .catch((error) => {
              Modal.alert(error.message, 'error');
            });
        },

        handleDelete() {
          const selectTableData = state.xTable.getSelectedRecords();
          // const len = state.selectTableData.length;

          if (selectTableData.length === 0) {
            Modal.alert('请选择要删除的数据！', 'warning');
            return false;
          }
          const isHasCode = selectTableData.some(
            (item) => item.RESOURCECOLUMN_CODE == 'rownumberer_1',
          );
          if (isHasCode) {
            Modal.alert('编码为rownumberer_1不可删除', 'info');
            return false;
          }
          Modal.confirm('确定删除选中的数据吗？', () => {
            methods.doDelete();
          });
        },

        // 删除
        doDelete() {
          const selectTableData = state.xTable.getSelectedRecords();
          const ids = selectTableData.map((item) => item.JE_CORE_RESOURCECOLUMN_ID).join(',');

          const params = {
            tableCode: 'JE_CORE_RESOURCECOLUMN',
            ids,
          };

          ListFieldConfigRemove(params)
            .then((res) => {
              Modal.message(res.message, 'success');
              selectTableData.forEach((item) => {
                state.tableData.remove(item);
              });
              // state.selectTableData = [];
              methods.getData();
            })
            .catch((error) => {
              Modal.alert(error.message, 'error');
            });
        },

        // 创建索引
        handleCreateIndex(row) {
          // 这边判断一下有没有修改
          const updateRecords = state.tableData.getChanges();
          if (updateRecords.length > 0) {
            Modal.alert('请先进行保存数据！', 'info');
            return false;
          }
          const params = {
            tableCode: 'JE_CORE_TABLEINDEX',
            funcId: state.funcId,
            TABLEINDEX_FIELDCODE: row.RESOURCECOLUMN_CODE,
            columnId: row.JE_CORE_RESOURCECOLUMN_ID,
          };

          ListFieldConfigCreateIndex(params, { pd: funcStore.product.code })
            .then((res) => {
              Modal.message(res.message, 'success');
              methods.getData();
            })
            .catch((error) => {
              Modal.alert(error.message, 'error');
            });
        },

        // 删除索引
        handleDeleteIndex(row) {
          const params = {
            tableCode: 'JE_CORE_TABLEINDEX',
            funcId: state.funcId,
            TABLEINDEX_FIELDCODE: row.RESOURCECOLUMN_CODE,
            columnId: row.JE_CORE_RESOURCECOLUMN_ID,
          };

          ListFieldConfigRemoveIndex(params, { pd: funcStore.product.code })
            .then((res) => {
              Modal.message(res.message, 'success');
              methods.getData();
            })
            .catch((error) => {
              Modal.alert(error.message, 'error');
            });
        },
        // 根据条件改变单元格的样式
        rowClassName({ row }) {
          if (row.RESOURCECOLUMN_CODE.substring(0, 3) == 'SY_') {
            return 'row-sys-cls';
          }
        },
        // 根据条件改变某一行的颜色
        cellClassName({ row, column }) {
          if (
            (column.property === 'RESOURCECOLUMN_NAME' ||
              column.property === 'RESOURCECOLUMN_CODE') &&
            row.RESOURCECOLUMN_CODE.substring(0, 3) == 'SY_'
          ) {
            return 'row-sys-cls';
          }
          // end
          return '';
        },
      };
      onBeforeMount(() => {
        // 获取字典数据
        loadDDItemByCodes([
          'JE_FUNC_QUERYTYPE',
          'JE_FUNC_COLUMN_XTYPE',
          'JE_FUNC_COLUMN_ALIGN',
        ]).then(() => {
          getDDItemList('JE_FUNC_COLUMN_ALIGN').map((item) => {
            state.COLUMN_ALIFN_LIST.push({ value: item.code, label: item.text });
          });
        });
      });
      onMounted(() => {
        nextTick(() => {
          methods.getData();
          VueEvent.off('refreshListFieldConfig');
          VueEvent.on('refreshListFieldConfig', () => {
            state.loading = true;
            methods.getData();
          });
        });
      });

      return {
        funcStore,
        ...toRefs(state),
        ...methods,
        modalOption,
        dataHeaderTable,
        handleJs,
        btnClick,
        menuActive,
      };
    },
  });
</script>
<style lang="less">
  .list-field-config {
    .radioGroup > .ant-radio-button-wrapper {
      padding: 0 15px !important;
    }

    .searchWrap {
      margin: 0 0 0 auto;
      .ant-input-search {
        border-bottom-right-radius: 0;
        border-top-right-radius: 0;
      }
      .ant-input-affix-wrapper-focused {
        box-shadow: none !important;
      }
      .ant-btn {
        width: 60px;
        background: #3265f5;
      }
    }
    .tableWrap {
      .table {
        .row-sys-cls {
          color: #3265f5;
        }
        .row-sys-cls td:nth-of-type(1),
        .row-sys-cls td:nth-of-type(2) {
          color: rgba(0, 0, 0, 0.85) !important;
        }
        .enable {
          background: #e0ffeb;
        }
        .close {
          background: #faf9da;
        }
      }
    }
    .vxe-table--empty-placeholder {
      display: none !important;
    }
    .navWrap {
      // padding-bottom: 10px;
      .vxe-table--body-wrapper,
      .vxe-table--empty-block {
        height: 20px !important;
        background: #fefed7;
        overflow-x: auto;
        overflow-y: hidden !important;
      }
    }
  }
</style>
<style lang="less" scoped>
  .list-field-config {
    // position: relative;
    width: 100%;
    height: 100%;
    .navWrap {
      ::-webkit-scrollbar {
        width: 4px;
        height: 4px;
      }
      width: 100%;
      background: #fefed7;
      > .vxe-table--body-wrapper {
        height: 20x !important;
        background: #fefed7;
      }
    }
    .navWrap::-webkit-scrollbar {
      width: 4px;
      height: 0px;
    }
    .top {
      display: flex;
      align-items: center;
      height: 40px;
      padding: 0 20px 0 4px;
      background: #f7f9fc;
      > .ant-btn {
        padding: 4px 12px !important;
        &:hover {
          color: #3f3f3f !important;
          background: #d9d9d9 !important;
        }
      }
    }
    .tableWrap {
      .table {
        .iconWrap {
          cursor: pointer;
        }
        .eventWrap {
          cursor: pointer;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .create,
        .remove {
          cursor: pointer;
        }
        .create {
          color: #3265f5;
        }
        .remove {
          color: #ff625c;
        }
      }
      .sider {
        background: #fff;
      }
    }
  }
</style>
